﻿using BootstrapBlazor.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocketBlazor.Models.Tcp;

namespace TouchSocketBlazor.ManagerService.TcpServiceManagers
{
    public class TcpServiceManager : ITcpServiceManager
    {
        readonly List<TcpServiceModel> m_serviceModels = new List<TcpServiceModel>();
        public Task<bool> AddAsync(TcpServiceModel model)
        {
            return Task.FromResult(true);
        }

        public Task<bool> DeleteAsync(IEnumerable<TcpServiceModel> models)
        {
            if (models != null)
            {
                foreach (var item in models)
                {
                    foreach (var target in m_serviceModels)
                    {
                        if (item.ID == target.ID)
                        {
                            this.m_serviceModels.Remove(target);
                            break;
                        }
                    }
                }
            }
            return Task.FromResult(true);
        }

        public Task<QueryData<TcpServiceModel>> QueryAsync(QueryPageOptions option)
        {
            QueryData<TcpServiceModel> queryData = new QueryData<TcpServiceModel>();
            queryData.Items = this.m_serviceModels.Where(a =>
            {
                return a.Name.Contains(option.SearchText ?? string.Empty);
            });

            return Task.FromResult(queryData);
        }

        public Task<bool> SaveAsync(TcpServiceModel model, ItemChangedType changedType)
        {
            switch (changedType)
            {
                case ItemChangedType.Add:
                    this.m_serviceModels.Add(model);
                    break;
                case ItemChangedType.Update:
                    if (model.ServerState== TouchSocket.Sockets.ServerState.Running)
                    {
                        return Task.FromResult(false);
                    }
                    var oldModel = this.m_serviceModels.FirstOrDefault(a => a.ID == model.ID);
                    if (oldModel != null)
                    {
                        this.m_serviceModels.Remove(oldModel);
                    }
                    this.m_serviceModels.Add(model);
                    break;
                default:
                    break;
            }
            return Task.FromResult(true);
        }
    }
}
